package org.chim.springcloud.eurekaserviceconsumer.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Class Name: HelloConsumerController
 * Create Date: 18-3-6 下午12:33
 * Creator: Chim·Zigui
 * Version: v1.0
 * Updater:
 * Date Time:
 * Description:
 */
@RestController
public class HelloConsumerController {

    @Autowired
    RestTemplate restTemplate;

    @Value(value = "${server.port}")
    private String port = null;

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/helloC", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @HystrixCommand(fallbackMethod = "fallbackHello")
    public Map hello(@RequestParam(value = "name", required = true) String name,
                     HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        ResponseEntity<Map> forEntity = restTemplate.getForEntity("http://SERVICE-HI-PROVIDER/hello/" + name, Map.class,
                parameterMap);
        Map body = forEntity.getBody();
        if (body != null) {
            body.put("ext", port);
            body.put("header", request.getHeader("x-label"));
        }
        return body;
    }

    public Map fallbackHello(@RequestParam(value = "name", required = true) String name, HttpServletRequest request) {
        Map<String, Object> fallbackResult = new HashMap<String, Object>();
        fallbackResult.put("code", -1);
        fallbackResult.put("msg", "默认");
        fallbackResult.put("hystrix", "default");
        return fallbackResult;
    }
}
